package org.hbnu.xiaomi.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.hbnu.xiaomi.entity.Carts;
import org.hbnu.xiaomi.entity.Goods;
import org.hbnu.xiaomi.entity.Orders;
import org.hbnu.xiaomi.entity.Users;
import org.hbnu.xiaomi.service.CartsService;
import org.hbnu.xiaomi.service.GoodsService;
import org.hbnu.xiaomi.service.OrdersService;
import org.hbnu.xiaomi.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

@Controller
public class CartsController {
    @Autowired
    CartsService cartsService;
    @Autowired
    UsersService usersService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    OrdersService ordersService;

    @RequestMapping("/saveCarts")
    @ResponseBody
    public String saveCarts(@RequestBody Map<String, String> maps, HttpServletRequest request) {
        //
        Integer user_id = (Integer) request.getSession().getAttribute("user_id");
        if (user_id == null) {
            return "用户没有登录";
        }

        //获取下单的商品编号和数量
        int good_id = Integer.parseInt(maps.get("good_id"));
        String numStr = maps.get("num");

        // 查询用户购物车中是否已经存在商品
        Integer oldnum = cartsService.getNumByGoodIdAndUserId(user_id, good_id);
        System.out.println("old:"+oldnum);
        if (oldnum == null) {
            oldnum = 0; // 如果没有旧记录，则设置为0
        }
        // 计算新的数量
        Integer newNum = oldnum + Integer.parseInt(numStr);
        System.out.println("new:"+newNum);

        // 删除旧的购物车记录
        cartsService.deleteByUserIdAndGoodId(user_id, good_id);

        // 创建新的购物车记录
        Carts carts = new Carts();
        carts.setGood_id(good_id);
        carts.setUser_id(user_id);
        carts.setNum(newNum);
        carts.setAllprice(goodsService.getById(good_id).getPrice() * newNum);
        System.out.println(goodsService.getById(good_id).getPrice() * newNum);
        carts.setOrdertime(new Timestamp(System.currentTimeMillis()));
        System.out.println("用户id"+user_id);
        System.out.println("商品id"+good_id);
        // 插入新的购物车记录
        cartsService.insert(carts);

        return "ok";

    }


    @RequestMapping("/deleteCart")
    @ResponseBody
    public String delete(@RequestBody Map<String, String> maps, HttpServletRequest request) {

        //获取要删除的购物车编号
        int id = Integer.parseInt(maps.get("id"));

        //获取购物车数据
        Carts carts = cartsService.getById(id);

        //判断用户登陆状态
        Integer user_id = (Integer) request.getSession().getAttribute("user_id");
        if (user_id == null) return "用户未登录！";
        if (carts == null) return "删除的购物车不存在";

        //删除购物车中的商品
        cartsService.deleteById(id);
        return "已删除";
    }


    @RequestMapping("/getCartsByUserId")
    @ResponseBody
    public List<Carts> getByUsersId(HttpServletRequest request){
        System.out.println("用户获取购物车");


        Integer user_id = (Integer) request.getSession().getAttribute("user_id");
        if (user_id == null) {
            System.out.println("用户没登录");
            return null;
        }
        System.out.println("用户id是"+user_id);
        List<Carts> cartsList = cartsService.getByUsersId(user_id);


        //设置购物车外键的关联实体
        for (Carts carts : cartsList) {
            System.out.println("carts.goodsId="+carts.getGood_id());
            Users user = usersService.getById(carts.getUser_id());
            carts.setUsers(user);
            carts.setGoods(goodsService.getById(carts.getGood_id()));
        }


        return cartsList;
    }




    @RequestMapping("/saveOrder")
    @ResponseBody
    public String saveOrder(HttpServletRequest request, @RequestBody List<OrderRequest> orderRequests) {
        Integer user_id = (Integer) request.getSession().getAttribute("user_id");
        if (user_id == null) {
            return "用户未登录";
        }

        for (OrderRequest orderRequest : orderRequests) {
            int good_id = orderRequest.getGood_id();
            int num = orderRequest.getNum();
            int paymentMethod = orderRequest.getPaymentMethod();

            Goods goods = goodsService.getById(good_id);
            if (goods == null) {
                return "商品编号 " + good_id + " 不存在";
            }
            if (num <= 0) {
                return "商品编号 " + good_id + " 的数量无效";
            }
            if (goods.getStock() < num) {
                return "no";
            }

            Orders order = new Orders();
            order.setGood_id(good_id);
            order.setUser_id(user_id);
            order.setNum(num);
            order.setOrdertime(new Timestamp(System.currentTimeMillis()));
            order.setPrice(new BigDecimal(num * goods.getPrice()));
            order.setPic(goods.getPic());
            order.setPaid(1);
            order.setPaymentMethod(paymentMethod);

            goods.setStock(goods.getStock() - num);

            goodsService.update(goods);
            ordersService.insert(order);
            if(num!=0) {
                cartsService.deleteByUserIdAndGoodId(user_id, good_id);
            }

        }

        return "ok";
    }

    public static class OrderRequest {
        private int good_id;
        private int num;
        private int paymentMethod;

        // Getters and Setters
        public int getGood_id() { return good_id; }
        public void setGood_id(int good_id) { this.good_id = good_id; }
        public int getNum() { return num; }
        public void setNum(int num) { this.num = num; }
        public int getPaymentMethod() { return paymentMethod; }
        public void setPaymentMethod(int paymentMethod) { this.paymentMethod = paymentMethod; }
    }


}
